<?php

namespace addons\shopro\listener;

use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\commission\Order as CommissionOrderModel;
use addons\shopro\service\commission\Order as OrderService;
use addons\shopro\service\commission\Reward as RewardService;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\Share as ShareModel;
use app\common\model\ScoreLog;
use think\Db;

class Commission
{

    /**
     * 用户注册成功
     */
    public function userRegisterAfter($payload)
    {
        $shareInfo = request()->param('shareInfo/a');

        if ($shareInfo) {
            // 注册后添加分享信息
            ShareModel::log($payload['user'], $shareInfo);
        }
        $agent = new AgentService($payload['user']);

        $agent->createNewAgent('user');
    }

    /**
     * 用户分享行为后
     */
    public function userShareAfter($payload)
    {
        $shareInfo = $payload['shareInfo'];

        if ($shareInfo) {

            $user_id = intval($shareInfo->user_id); // 受邀用户

            $share_id = intval($shareInfo->share_id); // 邀请人

            $agent = new AgentService($user_id);

            $bindCheck = $agent->bindUserRelation('share', $share_id);

            // 统计单链业绩
            if ($bindCheck) {
                $agent->createAsyncAgentUpgrade($user_id);
            }
        }
    }

    /**
     * 订单支付后
     */
    public function orderPaidAfter($params)
    {
        // 订单支付成功
        $order = $params['order'];

        // 积分商品订单不参与分销
        if ($order['type'] === 'score') return;

        $user = $params['user'];

        $agent = new AgentService($user["id"]);

        $user=$agent->user;//用户信息
        // 绑定用户关系
        $agent->bindUserRelation('pay');

        // 先记录分佣 再处理记录业绩、升级等情况
        $items = $order ? $order['items'] : [];

        //用户消费返积分比例
        $integralBackRate=Db::name("shopro_config")->where("code='shop.basic.integralback' and parent_code='shop.basic'")->value("value");

        $integral=0;//消费应返积分
        $prizeRecord=[];//有奖商品记录
        foreach ($items as $item) {
            if (isset($item['ext']['is_commission']) && !$item['ext']['is_commission']) continue;
            $goodsData=Db::name("shopro_goods")->where(["id"=>$item["goods_id"]])->field("id,is_prize,open_prize_time")->find();
            //这是会员卡专项 直接升级为分销商 并开通会员
            if($item["goods_id"]=="1"){
                $integral+=$item["goods_price"]*$item["goods_num"];
                $userDataNew=Db::name("user")
                    ->where(["id"=>$user["id"]])
                    ->field("egg_vip,egg_vip_start_time,egg_vip_end_time")->find();
                if($userDataNew){
                    $eggVip=[
                        "egg_vip"=>1,
                        "egg_vip_start_time"=>strtotime($userDataNew["egg_vip_end_time"]) >= time()?$userDataNew["egg_vip_start_time"]:date("Y-m-d H:i:s"),
                        "egg_vip_end_time"=>strtotime($userDataNew["egg_vip_end_time"]) >= time()?date('Y-m-d H:i:s', strtotime("{$userDataNew["egg_vip_end_time"]}+1 year")):date('Y-m-d H:i:s', strtotime("+1 year")),
                    ];
                    Db::name("user")->where(["id"=>$user["id"]])->update($eggVip);//开通鸡蛋会员或者续费鸡蛋会员
                }
            }elseif($user["egg_vip"] == "1" && strtotime($user["egg_vip_end_time"]) > time()){//判断是否是未过期鸡蛋会员 鸡蛋会员才返积分
                $integral+=round($item["goods_price"]*$item["goods_num"]*$integralBackRate* 0.01,2);
            }
            //有奖商品处理
            if($goodsData["is_prize"]=="yes"){
                $prizeRecord[]=[
                    "user_id"=>$item["user_id"],
                    "order_id"=>$order["order_sn"],
                    "goods_id"=>$item["goods_id"],
                    "code"=>date("YmdHis").rand(1000,9999),
                    "createtime"=>date("Y-m-d H:i:s"),
                    "open_prize_status"=>"wait",
                    "open_prize_time"=>$goodsData["open_prize_time"],
                ];
            }

            $commission = new OrderService($item);
            // 检查能否分销
            if (!$commission->checkAndSetCommission()) continue;

            // 添加分销订单
            $commissionOrder = $commission->createCommissionOrder();

            if (!$commissionOrder) continue;
            // 执行佣金计划
            $commission->runCommissionPlan($commissionOrder);

            // 支付后拨款
            (new RewardService('paid'))->runCommissionRewardByOrder($commissionOrder);
        }
        //将有奖记录添加到数据库
        if(!empty($prizeRecord)) Db::name("westts_goods_prize")->insertAll($prizeRecord);
        //执行积分计划##################################################
        if($order["use_integral"] > 0){//鸡蛋会员订单抵扣积分
            $lockIntegral=redis_cache("user_order_id".$user['id']);//获取锁定积分
            //解锁或重新加锁
            redis_cache("user_order_id".$user['id'],$lockIntegral > $order["use_integral"]?bcsub($lockIntegral,$order["use_integral"]):null);
            $this->handleIndegral($user["id"],$order["use_integral"],"dec");//积分处理
        }
        if($integral>0){//鸡蛋会员消费返积分
            $orderIntegral=round($order["pay_fee"]*$integralBackRate* 0.01,2);//总订单产生的积分
            if($integral>$orderIntegral)$integral=$orderIntegral;//如果子订单累加的积分大于总订单的积分就以总订单为准
            $this->handleIndegral($user["id"],$integral);//积分处理
        }
        //执行积分计划######################################################
        // 创建分销商
        $agent->createNewAgent();
        // 分销商数据统计&升级(异步执行) 暂时不进行分销升级
//        $agent->createAsyncAgentUpgrade();
    }
    //积分处理
    private function handleIndegral($userId,$integral,$type="inc"){
        $beforeIntegral=Db::name("user")->where(["id"=>$userId])->value("score");
        $scoreLogData=[
            "user_id"=>$userId,
            "score"=>$integral,
            "before"=>$beforeIntegral,
            "after"=>bcadd($beforeIntegral,$integral),
            "memo"=>$type=="inc"?"消费-用户直返积分":"消费-用户消耗积分",
            "createtime"=>time(),
        ];
        ScoreLog::create($scoreLogData);//添加用户积分记录
        if($type=="inc"){
            Db::name("user")->where(["id"=>$userId])->setInc("score",$integral);//用户增加积分
        }elseif ($type=="dec"){
            Db::name("user")->where(["id"=>$userId])->setDec("score",$integral);//用户消耗积分
        }

    }
    // 线下付款后
    public function orderOfflinePaidAfter($params)
    {
        $this->orderPaidAfter($params);
    }

    /**
     * 订单确认收货
     */
    public function orderConfirmFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('confirm');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单完成
     */
    public function orderFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('finish');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单退款后
     */
    public function orderItemRefundAfter($params)
    {
        $order = $params['order'];
        $item = $params['item'];

        $commissionOrder = CommissionOrderModel::where('order_id', $order->id)->where('order_item_id', $item->id)->find();

        if (!$commissionOrder) return;

        (new RewardService('refund'))->backCommissionRewardByOrder($commissionOrder);
    }
}
